#include "sem.h"
#include <time.h>
#include <unistd.h>

#define debug 1
#define P 0
#define V 1
int main(){
	unsigned short val[]={1,0};
	int semid=sem_create(2,val);
	char s[32];
	if(semid==-1){
		exit(1);
	}
	pid_t pid=fork();
	if(pid==-1){
		perror("fork:");
		exit(1);
	}
	if(pid==0){
		while(1){
			sem_occupy(semid,V);
			time_t now = time(NULL);
			strftime(s, sizeof s, "<%Y/%m/%d %X>", localtime(&now));
			printf("%s",s);
			fflush(stdout);
			sem_release(semid,P);
		}
	}else{
		char count=0;
		while(1){
			sem_occupy(semid,P);
			count++;
			printf("%d.",count);
			fflush(stdout);
			sem_release(semid,V);
			sem_occupy(semid,P);
			putchar('\n');	
#if debug
			if(count==10){
				kill(pid,SIGQUIT);
				break;
			}
#endif
			sem_release(semid,P);
		}
		wait(NULL);
	}
	return 0;
}
